package com.jhhc.Weathers.datasupplement.util;

import com.jhhc.Weathers.datasupplement.entity.BdmsWfProductF;
import com.jhhc.Weathers.datasupplement.entity.zksgBO.WindField;
import org.springframework.stereotype.Component;
import ucar.nc2.Attribute;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;
import ucar.nc2.dataset.NetcdfDataset;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class NC_util {

    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 雨量
     * @return
     * @throws IOException
     * @throws ParseException
     */
    public static List<BdmsWfProductF> readDate2(String path,int pid){
        //String NCFilepath = "D:\\work\\数据\\中科曙光nc\\PRATEsfc.nc";
        try {
            NetcdfFile ncfile = NetcdfDataset.open(path,null);
            Variable time = ncfile.findVariable("time");//时间
            Variable lat = ncfile.findVariable("lat");//纬度
            Variable lon = ncfile.findVariable("lon");//经度
            Variable PRATEsfc = ncfile.findVariable("PRATEsfc");//数据 ：时间 纬度 经度
            float[] time_list = (float[]) time.read().copyTo1DJavaArray();
            double[] lat_list = (double[]) lat.read().copyTo1DJavaArray();//纬度
            double[] lon_list = (double[]) lon.read().copyTo1DJavaArray();//经度
            float[][][]PRATEsfc_list = (float[][][]) PRATEsfc.read().copyToNDJavaArray();//数据 ：时间 纬度 经度
            ncfile.close();
            List<Attribute> attributes = time.getAttributes();
            String tm = String.valueOf(attributes.get(2).getValues()).substring(12);
            List<BdmsWfProductF> fList = new ArrayList<>();
            BdmsWfProductF bdmsWfProductF = null;
            String rtm1 = NC_util.dateAddyear(format.format(NC_util.dateAddyear(tm, (int) time_list[0])));
            for (int i = 0; i < time_list.length; i++) {
                int id = 0;
                String rtm = format.format(NC_util.dateAddyear(tm, (int) time_list[i]));
                for (int j = 0; j < lat_list.length; j++) {
                    for (int k = 0; k < lon_list.length; k++) {
                        bdmsWfProductF = new BdmsWfProductF();
                        bdmsWfProductF.setProvideid(pid);
                        bdmsWfProductF.setGridnm("China2.5km");
                        bdmsWfProductF.setRtm(rtm1);
                        bdmsWfProductF.setIntv(1);
                        bdmsWfProductF.setDtlen(NC_util.dateDvalue(rtm1,rtm));
                        bdmsWfProductF.setGridX(String.format("%.3f",lon_list[k]));
                        bdmsWfProductF.setGridY(String.format("%.3f",lat_list[j]));
                        bdmsWfProductF.setGridP(String.format("%.1f",PRATEsfc_list[i][j][k]));
                        bdmsWfProductF.setGridId(id);
                        fList.add(bdmsWfProductF);
                        id++;
                    }
                }
            }
            return fList;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取nc文件异常");
            return null;
        }
    }

    public static List<WindField> read(String pathV, String pathU, String pathS, String outPaht) throws IOException {
        System.out.println("读取文件");
        NetcdfFile netcdfFileV = NetcdfDataset.open(pathV);
        NetcdfFile netcdfFileU = NetcdfDataset.open(pathU);
        NetcdfFile netcdfFileS = NetcdfDataset.open(pathS);
        Variable variableV = netcdfFileV.findVariable("VGRD10m");
        Variable variableU = netcdfFileU.findVariable("UGRD10m");
        Variable variableS = netcdfFileS.findVariable("slp");
        Variable time = netcdfFileS.findVariable("time");//时间
        Variable lat = netcdfFileS.findVariable("lat");//纬度
        Variable lon = netcdfFileS.findVariable("lon");//经度
        float[] timeList = (float[]) time.read().copyTo1DJavaArray();//时间
        double[] latList = (double[]) lat.read().copyTo1DJavaArray();//纬度
        double[] lonList = (double[]) lon.read().copyTo1DJavaArray();//经度
        double[][][] v = (double[][][]) variableV.read().copyToNDJavaArray();
        double[][][] u = (double[][][]) variableU.read().copyToNDJavaArray();
        float[][][] s = (float[][][]) variableS.read().copyToNDJavaArray();
        List<Attribute> attributes = time.getAttributes();
        String tm = String.valueOf(attributes.get(2).getValues()).substring(12);
        System.out.println(tm);
        netcdfFileV.close();
        netcdfFileU.close();
        netcdfFileS.close();
        List<WindField> windFields = new ArrayList<>();
        String rtm = null;
        File file2 = new File(outPaht);
        FileOutputStream fos = new FileOutputStream(file2,true);
        String startTime = format.format(NC_util.dateAddyear(tm, (int)timeList[0]));
        String endTime = format.format(NC_util.dateAddyear(tm, (int)timeList[timeList.length-1]));
        String s1 = "";
        String s2 = "";
        String s3 = "";
        String valueV;
        String valueU;
        String valueS;
        String t = "spatial resolution:0.1" + "   startTime:" + startTime + "   endTime:" + endTime;
        byte[] sBytes;
        sBytes  = t.getBytes();
        fos.write(sBytes);
        for (int i = 0; i < timeList.length; i++) {
            rtm = format.format(NC_util.dateAddyear(tm, (int) timeList[i]));
            rtm = "\r\n" + rtm;
            sBytes  = rtm.getBytes();
            fos.write(sBytes);
            System.out.println(rtm);
            for (int j = latList.length - 1; j >= 0; j--) {//大-小
                if (latList[j] <= 41.5 && latList[j] >= 24.5) {
                    for (int k = 0; k < lonList.length; k++) {//小-大
                        if (lonList[k] >= 117 && lonList[k] <= 130) {
                            valueV = String.format("%E",v[i][j][k]);
                            valueU = String.format("%E",u[i][j][k]);
                            valueS = String.format("%.6f",s[i][j][k]);
                            s1 = Double.parseDouble(valueV) >= 0 ? "    " + valueV:"   " + valueV;
                            s2 = Double.parseDouble(valueU) >= 0 ? "    " + valueU:"   " + valueU;
                            s3 = Double.parseDouble(valueS) < 1000 ? "    " + valueS + "0":"    " + valueS;
                            sBytes = ("\r\n" + s1 + s2 + s3).getBytes();
                            fos.write(sBytes);
                        }
                    }
                }
            }
        }
        fos.flush();
        fos.close();
        return windFields;
    }

    public static int readB(String pathV,String pathU,String pathS,String windSiteFile,String region){

        long startTime1 = System.currentTimeMillis();
        try {
            String[] strings = region.split(",");
            System.out.println(Arrays.toString(strings));
//            double startLat = Double.parseDouble(strings[2]);
//            double endLat = startLat - (Double.parseDouble(strings[0]) * Double.parseDouble(strings[4]));
//            double startLon = Double.parseDouble(strings[3]);
//            double endLon = startLon + (Double.parseDouble(strings[1]) * Double.parseDouble(strings[4]));
            double startLat = Double.parseDouble(strings[1]);
            double endLat = Double.parseDouble(strings[3]);
            double startLon = Double.parseDouble(strings[0]);
            double endLon = Double.parseDouble(strings[2]);
            System.out.println(startLat);
            System.out.println(endLat);
            System.out.println(startLon);
            System.out.println(endLon);
            //windSiteFile = windSiteFile + File.separator + "fort.22";
            NetcdfFile netcdfFileV = NetcdfDataset.open(pathV);
            NetcdfFile netcdfFileU = NetcdfDataset.open(pathU);
            NetcdfFile netcdfFileS = NetcdfDataset.open(pathS);
            Variable variableV = netcdfFileV.findVariable("VGRD10m");
            Variable variableU = netcdfFileU.findVariable("UGRD10m");
            Variable variableS = netcdfFileS.findVariable("slp");
            Variable time = netcdfFileS.findVariable("time");//时间
            Variable lat = netcdfFileS.findVariable("lat");//纬度
            Variable lon = netcdfFileS.findVariable("lon");//经度
            float[] timeList = (float[]) time.read().copyTo1DJavaArray();//时间
            System.out.println("timeList:" + timeList.length);
            double[] latList = (double[]) lat.read().copyTo1DJavaArray();//纬度
            double[] lonList = (double[]) lon.read().copyTo1DJavaArray();//经度
            double[][][] v = (double[][][]) variableV.read().copyToNDJavaArray();
            double[][][] u = (double[][][]) variableU.read().copyToNDJavaArray();
            float[][][] s = (float[][][]) variableS.read().copyToNDJavaArray();
            List<Attribute> attributes = time.getAttributes();
            String tm = String.valueOf(attributes.get(2).getValues()).substring(12);
            netcdfFileV.close();
            netcdfFileU.close();
            netcdfFileS.close();
            //String rtm = null;
            File file = new File(windSiteFile);
            FileOutputStream fos = new FileOutputStream(file,true);
            String startTime = format.format(NC_util.dateAddyear(tm, (int)timeList[0]));
//            String endTime = format.format(NC_util.dateAddyear(tm, (int)timeList[timeList.length-1]));
            StringBuilder s1 = new StringBuilder();
            String valueV,valueS,valueU;
            byte[] sBytes;
            s1.append("spatial resolution:0.1").append("   startTime:").append(startTime).append("   endTime:").append("2023-09-04 23:00:00")
                    .append("\r\n");
            for (int i = 0; i < timeList.length; i++) {//时间
                String rtm = format.format(NC_util.dateAddyear(tm, (int) timeList[i]));
                System.out.println(rtm);
                if ("2023-09-05 00:00:00".equals(rtm)) {
                    break;
                }
                s1.append(rtm).append("\r\n");
                for (int j = latList.length - 1; j >= 0; j--) {//纬度 大-小
                    if (latList[j] <= startLat && latList[j] >= endLat) {
                        for (int k = 0; k < lonList.length; k++) {//经度 小-大
                            if (lonList[k] >= startLon && lonList[k] <= endLon) {
                                valueV = String.format("%E",v[i][j][k]);
                                valueU = String.format("%E",u[i][j][k]);
                                valueS = String.format("%.6f",s[i][j][k]);
                                s1.append(Double.parseDouble(valueV) >= 0 ? "    " + valueV:"   " + valueV)
                                    .append(Double.parseDouble(valueU) >= 0 ? "    " + valueU:"   " + valueU)
                                    .append(Double.parseDouble(valueS) < 1000 ? "    " + valueS + "0":"    " + valueS)
                                        .append("\r\n");
                            }
                        }
                    }
                }
                sBytes = s1.toString().getBytes();
                fos.write(sBytes);
                s1 = new StringBuilder();
            }
            fos.flush();
            fos.close();
            long endTime1 = System.currentTimeMillis();
            float excTime = (float)(endTime1 - startTime1) / 1000;
            System.out.println("解析生成风场文件耗时：" + excTime + "s");
            return 1;
        } catch (IOException e) {
            e.printStackTrace();
            long endTime1 = System.currentTimeMillis();
            float excTime = (float)(endTime1 - startTime1) / 1000;
            System.out.println("文件解析异常耗时：" + excTime + "s");
            return 0;
        }

    }


    //日期转换
    public static Date dateAddyear(String tm,int datenum) {
        Date date = null;
        try {
            date = format.parse(tm);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.HOUR,datenum + 8);
            return cal.getTime();
        }catch (ParseException e){
            System.out.println("时间格式异常");
            return null;
        }
    }
    public static String dateAddyear(String tm) {
        Date date = null;
        try {
            date = format.parse(tm);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.HOUR,-1);
            return format.format(cal.getTime());
        }catch (ParseException e){
            System.out.println("时间格式异常");
            return null;
        }
    }
    //时间差
    public static int dateDvalue(String tm1,String tm2) {
//        System.out.println(tm1);
//        System.out.println(tm2);
        if (tm1 == null || "".equals(tm1) || tm2 == null || "".equals(tm2)) {
            return 0;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String startTm = format.format(tm1);
//        String endTm = format.format(tm2);
        long from = 0;
        long to = 0;
        try {
            from = format.parse(tm1).getTime();
            to = format.parse(tm2).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("时间转化异常：dateDvalue");
        }
        return (int) ((to - from)/(1000 * 60 * 60));
    }
//    /**
//     *风压
//     */
//    public static List<BdmsFbcResultA> readDate3(String path) throws IOException, ParseException {
//        //String NCFilepath = "D:\\work\\数据\\中科曙光nc\\slp.nc";
//        NetcdfFile ncfile = NetcdfDataset.open(path,null);
//        Variable time = ncfile.findVariable("time");//时间
//        Variable lat = ncfile.findVariable("lat");//纬度
//        Variable lon = ncfile.findVariable("lon");//经度
//        Variable slp = ncfile.findVariable("slp");//数据 ：时间 纬度 经度
//        float[] time_list = (float[]) time.read().copyTo1DJavaArray();//时间
//        double[] lat_list = (double[]) lat.read().copyTo1DJavaArray();//纬度
//        double[] lon_list = (double[]) lon.read().copyTo1DJavaArray();//经度
//        float[][][]PRATEsfc_list = (float[][][]) slp.read().copyToNDJavaArray();//数据 ：时间 纬度 经度
//        List<Attribute> attributes = time.getAttributes();
//        String tm = String.valueOf(attributes.get(2).getValues()).substring(12);
//        List<BdmsFbcResultA> bdmsFbcResultAS = new ArrayList<>();
//        BdmsFbcResultA BdmsFbcResultA = null;
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        StringBuilder p = new StringBuilder();
//        int valuei = 0;
//        for (int i = 0; i < time_list.length; i++) {
//            BdmsFbcResultA = new BdmsFbcResultA();
//            String rtm = format.format(NC_util.dateAddyear(tm, (int) time_list[i]));
//            BdmsFbcResultA.setCschemeid("2023");
//            BdmsFbcResultA.setAreaname("浙江");
//            BdmsFbcResultA.setDtid(i);
//            BdmsFbcResultA.setDttm(rtm);
//            BdmsFbcResultA.setDttp(13);
//            for (int j = 0; j < lat_list.length; j++) {
//                for (int k = 0; k < lon_list.length; k++) {
//                    valuei = (int)Double.parseDouble(String.format("%.2f",PRATEsfc_list[i][j][k])) * 100;
//                    p.append(valuei).append(",");
//                }
//            }
//            BdmsFbcResultA.setDtvalues(p.toString());
//            p = new StringBuilder();
//            bdmsFbcResultAS.add(BdmsFbcResultA);
//        }
//        return bdmsFbcResultAS;
//    }
//
//    /**
//     * 风速
//     */
//    public static List<BdmsFbcResultA> readDate4(String path) throws IOException, ParseException {
//        //String NCFilepath = "D:\\work\\数据\\中科曙光nc\\VGRD10m.nc";
//        NetcdfFile ncfile = NetcdfDataset.open(path,null);
//        Variable time = ncfile.findVariable("time");//时间
//        Variable lat = ncfile.findVariable("lat");//纬度
//        Variable lon = ncfile.findVariable("lon");//经度
//        Variable VGRD10m = ncfile.findVariable("VGRD10m");//数据 ：时间 纬度 经度
//        float[] time_list = (float[]) time.read().copyTo1DJavaArray();//时间
//        double[] lat_list = (double[]) lat.read().copyTo1DJavaArray();//纬度
//        double[] lon_list = (double[]) lon.read().copyTo1DJavaArray();//经度
//        double[][][]PRATEsfc_list = (double[][][]) VGRD10m.read().copyToNDJavaArray();//数据 ：时间 纬度 经度
//        List<Attribute> attributes = time.getAttributes();
//        String tm = String.valueOf(attributes.get(2).getValues()).substring(12);
//        List<BdmsFbcResultA> bdmsFbcResultAS = new ArrayList<>();
//        BdmsFbcResultA bdmsFbcResultA = null;
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        StringBuilder p = new StringBuilder();
//        int valuei = 0;
//        for (int i = 0; i < time_list.length; i++) {
//            String rtm = format.format(NC_util.dateAddyear(tm, (int) time_list[i]));
//            bdmsFbcResultA = new BdmsFbcResultA();
//            bdmsFbcResultA.setCschemeid("2023");
//            bdmsFbcResultA.setAreaname("浙江");
//            bdmsFbcResultA.setDtid(i);
//            bdmsFbcResultA.setDttm(rtm);
//            bdmsFbcResultA.setDttp(17);
//            for (int j = 0; j < lat_list.length; j++) {
//                for (int k = 0; k < lon_list.length; k++) {
//                    valuei = (int)Double.parseDouble(String.format("%.2f",PRATEsfc_list[i][j][k])) * 100;
//                    p.append(valuei).append(",");
//                }
//            }
//            bdmsFbcResultA.setDtvalues(p.toString());
//            p = new StringBuilder();
//            bdmsFbcResultAS.add(bdmsFbcResultA);
//        }
//        return bdmsFbcResultAS;
//    }
//
//    /**
//     * 风向
//     * @return
//     * @throws IOException
//     * @throws ParseException
//     */
//    public static List<BdmsFbcResultA> readDate5() throws IOException, ParseException {
//        String NCFilepath = "D:\\work\\数据\\中科曙光nc\\UGRD10m.nc";
//        NetcdfFile ncfile = NetcdfDataset.open(NCFilepath,null);
//        Variable time = ncfile.findVariable("time");//时间
//        Variable lat = ncfile.findVariable("lat");//纬度
//        Variable lon = ncfile.findVariable("lon");//经度
//        Variable UGRD10m = ncfile.findVariable("UGRD10m");//数据 ：时间 纬度 经度
//        float[] time_list = (float[]) time.read().copyTo1DJavaArray();//时间
//        double[] lat_list = (double[]) lat.read().copyTo1DJavaArray();//纬度
//        double[] lon_list = (double[]) lon.read().copyTo1DJavaArray();//经度
//        double[][][]PRATEsfc_list = (double[][][]) UGRD10m.read().copyToNDJavaArray();//数据 ：时间 纬度 经度
//        List<Attribute> attributes = time.getAttributes();
//        String tm = String.valueOf(attributes.get(2).getValues()).substring(12);
//        List<BdmsFbcResultA> bdmsFbcResultAS = new ArrayList<>();
//        BdmsFbcResultA bdmsFbcResultA = null;
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        StringBuilder p = new StringBuilder();
//        int valuei = 0;
//        for (int i = 0; i < time_list.length; i++) {
//            System.out.println(time_list[i]);
//            String rtm = format.format(NC_util.dateAddyear(tm, (int) time_list[i]));
//            bdmsFbcResultA = new BdmsFbcResultA();
//            bdmsFbcResultA.setCschemeid("2023");
//            bdmsFbcResultA.setAreaname("浙江");
//            bdmsFbcResultA.setDtid(i);
//            bdmsFbcResultA.setDttm(rtm);
//            bdmsFbcResultA.setDttp(17);
//            for (int j = 0; j < lat_list.length; j++) {
//                for (int k = 0; k < lon_list.length; k++) {
//                    valuei = (int)Double.parseDouble(String.format("%.2f",PRATEsfc_list[i][j][k])) * 100;
//                    p.append(valuei).append(",");
//                }
//            }
//            bdmsFbcResultA.setDtvalues(p.toString());
//            p = new StringBuilder();
//            bdmsFbcResultAS.add(bdmsFbcResultA);
//        }
//        return bdmsFbcResultAS;
//    }

}
